package top.dark.transaction;

import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;

/**
 * Author: Darkn
 * description:
 * Create Time: 2021/5/4 20:06
 */
public class JmsProducer {
    private final static String ACTIVEMQ_URL = "tcp://192.168.136.181:61616";
    private final static String ACTIVEMQ_QUEUE = "transaction_queue";
    public static void main(String[] args) throws JMSException {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        Connection connection = factory.createConnection();
        connection.start();
        // true代表开启事务
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(ACTIVEMQ_QUEUE);
        MessageProducer producer = session.createProducer(queue);
        try {
            for (int i = 0; i < 4; i++) {
                TextMessage message = session.createTextMessage("" + i);
                producer.send(message);
            }
            // 提交事务
            session.commit();
            System.out.println("消息发送完成");
        } catch (Exception e) {
            System.out.println("出现异常,消息回滚");
            session.rollback();
        }
        producer.close();
        session.close();
        connection.close();
    }
}
